package com.station.Activitys.activity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.station.Activitys.R;
import com.station.Activitys.activity.base.BaseMapActivity;
import com.station.Activitys.adapter.WindowAdapter;
import com.station.Activitys.bean.WorkMapMsg;
import com.station.Activitys.http.manager.WorkManager;
import com.station.Activitys.utils.CacheManger;
import com.station.Activitys.utils.Constant;
import com.station.Activitys.utils.ToastUtils;
import com.zhy.autolayout.AutoLinearLayout;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：基站管理平台 手机app
 * 类描述：基站分布地图
 * 创建人：张飞祥
 * 创建时间：2018/11/13 10:09
 * 修改人：张飞祥
 * 修改时间：2018/11/13 10:09
 * 修改备注：
 */
public class MapStationActivity extends BaseMapActivity implements LocationSource, AMapLocationListener, RadioGroup.OnCheckedChangeListener {

    //返回按钮
    @Bind(R.id.iv_return) ImageView ivReturn;
    //标题
    @Bind(R.id.tv_title) TextView tvTitle;
    //地图
    @Bind(R.id.map_location) MapView mMapView;
    //定位
    @Bind(R.id.iv_location) ImageView ivLocation;
    //放大地图
    @Bind(R.id.iv_zoom_plus) ImageView ivZoomPlus;
    //缩小地图
    @Bind(R.id.iv_zoom_reduce) ImageView ivZoomReduce;
    //抽屉按钮
    @Bind(R.id.iv_drawer) ImageView ivDrawer;
    //地图坐标详情
    @Bind(R.id.layout_map_msg) AutoLinearLayout layoutMapMsg;
    //单选按钮 管理者
    @Bind(R.id.rg_station) RadioGroup rgStation;

    //TODO 变量
    //初始化网络请求
    public WorkManager mApiManager;

    //用户 id
    private int mUserId;
    //网络请求 type
    private String mMapType = "全部";
    //抽屉标记 true：开启抽屉 false：关闭抽屉
    private boolean mDrawerFlag = false;

    //初始化地图控制器对象
    private AMap aMap;
    //声明 高德地图 定位监听
    private OnLocationChangedListener mListener;
    //声明 高德地图 AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明 高德地图 AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    //声明 坐标点 集合
    private ArrayList<Marker> mMarkerList = new ArrayList<>();
    //TODO 地图缩放参数
    //位置
    private CameraPosition mCameraPosition;
    //现在缩放大小
    private float mMapZoom;
    //缩放后经纬度
    private LatLng mMapTarget;

    @Override
    protected void initUI(Bundle savedInstanceState) {
        setContentView(R.layout.layout_base_station_map);
        //网络请求接口 常驻方法
        mApiManager = mApiManager.getWorkApiManager(this, this.getTaskId());
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //获取 用户 id
        mUserId = CacheManger.getUserId(mACache);

        //TODO 初始化地图配置信息
        if (aMap == null) {
            aMap = mMapView.getMap();
            //获取UiSettings实例
            UiSettings ui = aMap.getUiSettings();
            //设置缩放控件
            ui.setZoomControlsEnabled(false);
            //隐藏logo
            ui.setLogoBottomMargin(-50);
            // 初始化地图 缩放大小
            aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
            // 设置定位监听
            aMap.setLocationSource(this);
            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);
        }

        //TODO 初始化UI布局
        //设置标题
        tvTitle.setText("基站分布图");
    }

    @Override
    protected void initData() {
        //单选按钮监听事件
        rgStation.setOnCheckedChangeListener(this);
        //初始化基站分布信息
        initPostHttp();
    }

    /**
     * 开始网络请求 基站分布信息
     */
    private void initPostHttp() {
        //显示加载提示dialog
        initShowTimeDialog("正在加载基站分布信息，请稍后....", this);
        //开始网络请求
        mApiManager.workMapLocationMsg(mUserId, mMapType);
    }

    /**
     * 工单变更 基站分布信息 解析报错
     */
    @Subscriber(tag = Constant.BUS_WORK_MAP_MSG_LIST_ERROR, mode = ThreadMode.MAIN)
    public void initHttpError(String strError) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏dialog
                mTimeDialog.dismiss();
                //弹出相应的提示
                ToastUtils.showShort(MapStationActivity.this, Constant.NETWORK_ERROR_MSG);
            }
        }, 1000);
    }

    /**
     * 工单变更 基站分布信息 数据返回成功
     */
    @Subscriber(tag = Constant.BUS_WORK_MAP_MSG_LIST, mode = ThreadMode.MAIN)
    public void initHttpData(final List<WorkMapMsg> list) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //隐藏dialog
                mTimeDialog.dismiss();
                //TODO 填充坐标点数据
                if (list != null && list.size() > 0) {
                    for (WorkMapMsg map : list) {
                        //循环添加坐标点
                        addMapLocation(map);
                    }
                }
            }
        }, 1000);
    }

    /**
     * 动态添加基站 地图坐标点
     */
    public void addMapLocation(final WorkMapMsg map) {
        //添加坐标点
        LatLng latLng = new LatLng(map.getGPS_Y(), map.getGPS_X());
        MarkerOptions marker = new MarkerOptions();

        //设置坐标
        marker.position(latLng);
        //设置标题
        marker.title("名称：" + map.getPhysicalStationName());
        //设置内容
        marker.snippet("地址：" + map.getAddressOfPhysicalStation());

        /**
         * 根据不同的 type，设置不同的动态坐标点
         *
         * 1.勘察 ----> 蓝色坐标点
         * 1.规划 ----> 绿色坐标点
         * 1.可研 ----> 黄色坐标点
         * 1.变更 ----> 红色坐标点
         *
         */
        ArrayList<BitmapDescriptor> imgMapList = new ArrayList<>();
        String type = map.getType();
        if ("勘察".equals(type)) {          //蓝色
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_blue_one));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_blue_two));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_blue_three));
        } else if ("规划".equals(type)) {   //绿色
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_green_one));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_green_two));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_green_three));
        } else if ("可研".equals(type)) {   //黄色
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_yellow_one));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_yellow_two));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_yellow_three));
        } else if ("变更".equals(type)) {   //红色
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_red_one));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_red_two));
            imgMapList.add(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_red_three));
        }
        //添加 坐标点图片集合
        marker.icons(imgMapList);
        //设置刷新速度，越小越快
        marker.period(35);
        //添加窗体自定义布局
        WindowAdapter adapter = new WindowAdapter(MapStationActivity.this);
        //绑定信息窗点击事件
        aMap.setOnMapClickListener(adapter);
        //设置自定义弹窗
        aMap.setInfoWindowAdapter(adapter);
        //将当前坐标点 添加到地图上
        //将当前坐标点添加到集合中
        mMarkerList.add(aMap.addMarker(marker));
    }

    /**
     * 按钮点击事件
     *
     * @return
     */
    @OnClick({R.id.iv_return, R.id.iv_location, R.id.iv_zoom_plus,
            R.id.iv_zoom_reduce,R.id.iv_drawer})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_return:         //返回
                finish();
                break;

            case R.id.iv_location:       //定位
                startLocation();
                break;

            case R.id.iv_zoom_plus:      //放大地图
                scaleLargeMap(true);
                break;

            case R.id.iv_zoom_reduce:    //缩小地图
                scaleLargeMap(false);
                break;

            case R.id.iv_drawer:         //抽屉
                if (mDrawerFlag)
                    isShowDrawer();
                else
                    isNotShowDrawer();
                break;
        }
    }


    /**
     * 单选按钮点击事件
     * @param radioGroup
     * @param id
     */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (id){

            case R.id.rb_station_all:       //全部
                mMapType = "全部";
                break;
            case R.id.rb_station_survey:    //勘察
                mMapType = "勘察";
                break;
            case R.id.rb_station_plan:      //规划
                mMapType = "规划";
                break;
            case R.id.rb_station_study:     //可研
                mMapType = "可研";
                break;
            case R.id.rb_station_change:    //变更
                mMapType = "变更";
                break;
        }
        //清除所有坐标点
        clearAllMarker();
        //开始网络请求
        initPostHttp();
    }

    /**
     * 清除所有Marker
     */
    public void clearAllMarker() {
        for (Marker marker : mMarkerList) {
            marker.remove();
        }
        mMarkerList.clear();
    }

    /**
     * 高德地图 放大缩小 调用方法
     */
    public void scaleLargeMap(boolean zoomFlag) {
        mCameraPosition = aMap.getCameraPosition();
        mMapZoom = mCameraPosition.zoom;
        mMapTarget = mCameraPosition.target;
        if (zoomFlag)
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mMapTarget, ++mMapZoom));
        else
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mMapTarget, --mMapZoom));
    }


    /**
     * 定位参数配置
     *
     * @param onLocationChangedListener
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient == null) {
            //开始定位
            startLocation();
        }
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        MyLocationStyle style = new MyLocationStyle();//初始化定位蓝点样式类
        // 定位一次，且将视角移动到地图中心点。
        style.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        // 设置圆形的边框颜色
        style.strokeColor(Color.argb(0, 0, 0, 0));
        // 设置圆形的填充颜色
        style.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 设置小蓝点的图标
        style.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.ic_map_my_location));
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(style);

        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 启动定位
        mLocationClient.startLocation();
    }

    /**
     * 销毁定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    /**
     * 设置定位回调监听
     *
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {

            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
            // 停止定位
            mLocationClient.stopLocation();
        }
    }

    /**
     * 显示 筛选 视图
     */
    private void isShowDrawer() {
        //抽屉 flag
        mDrawerFlag = false;
        //显示抽屉
        layoutMapMsg.setVisibility(View.VISIBLE);
        //设置抽屉角标（右侧）
        ivDrawer.setImageResource(R.drawable.img_map_msg_right);
    }

    /**
     * 隐藏 筛选 视图
     */
    private void isNotShowDrawer() {
        //抽屉 flag
        mDrawerFlag = true;
        //设置抽屉角标（左侧）
        ivDrawer.setImageResource(R.drawable.img_map_msg_left);
        //隐藏抽屉
        layoutMapMsg.setVisibility(View.GONE);
    }


    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
}
